//
//  HttpManager.m
//  Booking
//
//  Created by Duntech on 2018/4/18.
//  Copyright © 2018年 Duntech. All rights reserved.
//

#import "HttpManager.h"
#import "HYBaseNetworkModel.h"

static AFHTTPSessionManager *manager;

@implementation HttpManager

+ (instancetype)shareHTTPManager{
    
    static HttpManager *httpManager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        httpManager = [HttpManager new];
        manager = [AFHTTPSessionManager manager];
        httpManager.reachabilityManager = manager.reachabilityManager;
    });
    return httpManager;
}

#pragma mark -- GET

- (void)getDataFromUrl:(NSString *)url withParameter:(NSDictionary *)para showHUDView:(UIView *)view success:(requestSuccess)successBlock{
    
    if (view) [MBProgressHUD showPregressHUD:view];
    
    NSString *urlString= [NSString stringWithFormat:@"%@/%@",API_DomainStr,url];
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/plain", @"text/html", nil];
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    // 设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 10.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    manager.securityPolicy.allowInvalidCertificates = YES;
    
    NSString *token = @"";
    NSTimeInterval currentTimeStamp = ([[NSDate date] timeIntervalSince1970] + 8 * 60 * 60) * 1000;
    NSString *timestamp = [NSString stringWithFormat:@"%f",currentTimeStamp];
    if ([HYUserModel sharedInstance].token) {
        token = [NSString stringWithFormat:@"token %@",[HYUserModel sharedInstance].token];
    }
    [manager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:timestamp forHTTPHeaderField:@"Access-TimeSpan"];
    
    NSLog(@"URL:%@\nPara:%@ \n",urlString,para);
    [manager GET:urlString parameters:para progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"responseObject:%@",responseObject);
        if (responseObject){
            
            HYBaseNetworkModel *baseModel = [HYBaseNetworkModel modelWithDictionary:responseObject];
            if ([baseModel.code isEqualToString:KSUCCESS]) {
                //成功
                successBlock(baseModel);
            }
            else{
                successBlock(nil);
            }
        }
        else{
            
            [JRToast showWithText:NSLocalizedString(@"interfaceError", nil) bottomOffset:60 duration:2.0];
            successBlock(nil);
        }
        
        if (view) [MBProgressHUD hidePregressHUD:view];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Error:%@",error);
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [JRToast showWithText:NSLocalizedString(@"serverError", nil) bottomOffset:60 duration:2.0];
            if (view) [MBProgressHUD hidePregressHUD:view];
        });
        successBlock(nil);
    }];
}

#pragma mark -- POST

- (void)postDataFromUrl:(NSString *)url withParameter:(NSDictionary *)para showHUDView:(UIView *)view success:(requestSuccess)successBlock{
    
    if (view) [MBProgressHUD showPregressHUD:view];
    
    NSString *urlString= [NSString stringWithFormat:@"%@/%@",API_DomainStr,url];
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/plain", nil];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    //设置请求头
//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    //采用JSON的方式来解析数据
    //    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    // 设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 10.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    NSString *token = @"";
    NSTimeInterval currentTimeStamp = [[NSDate date] timeIntervalSince1970] * 1000;
    NSString *timestamp = [NSString stringWithFormat:@"%.0f",currentTimeStamp];
//    if ([HYUserModel sharedInstance].token) {
//        token = [NSString stringWithFormat:@"token %@",[HYUserModel sharedInstance].token];
//    }
//    [manager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:timestamp forHTTPHeaderField:@"Access-TimeSpan"];
    
    NSLog(@"URL:%@\nPara:%@ \n",urlString,para);
    [manager POST:urlString parameters:para progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"responseObject:%@",responseObject);
        if (responseObject){
            
            HYBaseNetworkModel *baseModel = [HYBaseNetworkModel modelWithDictionary:responseObject];
//            if ([baseModel.code isEqualToString:KSUCCESS]) {
//
//                [[HYUserModel sharedInstance] logout];
//                [JRToast showWithText:baseModel.code duration:3];
//                successBlock(nil);
//                return;
//            }
            
            if ([baseModel.code isEqualToString:KSUCCESS]) {
                //成功
                successBlock(baseModel);
            }
            else{
                
                [JRToast showWithText:baseModel.msg bottomOffset:60 duration:2.0];
                successBlock(nil);
            }
        }
        else{
            [JRToast showWithText:NSLocalizedString(@"interfaceError", nil) bottomOffset:60 duration:2.0];
            successBlock(nil);
        }
        
        if (view) [MBProgressHUD hidePregressHUD:view];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Error:%@",error);
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [JRToast showWithText:NSLocalizedString(@"serverError", nil) bottomOffset:60 duration:2.0];
            if (view) [MBProgressHUD hidePregressHUD:view];

        });
        successBlock(nil);
    }];
}

- (void)uploadDataFromUrl:(NSString *)url withParameter:(NSDictionary *)para data:(NSData *)data showHUDView:(UIView *)view success:(requestSuccess)successBlock{
    
    if (view) {
        
        
        
    }
    NSString *urlString= [NSString stringWithFormat:@"%@/%@",API_DomainStr,url];
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];

    [manager POST:urlString parameters:para constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        //上传图片
        [formData appendPartWithFileData:data name:@"head" fileName:@"headerImage" mimeType:@"image/jpg/png/jpeg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        successBlock(responseObject);
    }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        successBlock(nil);
    }];
}

#pragma mark -- DELETE

- (void)deleteDataFromUrl:(NSString *)url withParameter:(NSDictionary *)para showHUDView:(UIView *)view success:(requestSuccess)successBlock{
    
    if (view) [MBProgressHUD showPregressHUD:view];
    
    NSString *urlString= [NSString stringWithFormat:@"%@/%@",API_DomainStr,url];
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/plain", nil];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    // 设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 10.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    NSString *token = @"";
    NSTimeInterval currentTimeStamp = [[NSDate date] timeIntervalSince1970] * 1000;
    NSString *timestamp = [NSString stringWithFormat:@"%.0f",currentTimeStamp];
    //    if ([HYUserModel sharedInstance].token) {
    //        token = [NSString stringWithFormat:@"token %@",[HYUserModel sharedInstance].token];
    //    }
    //    [manager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:timestamp forHTTPHeaderField:@"Access-TimeSpan"];
    
    NSLog(@"URL:%@\nPara:%@ \n",urlString,para);
    [manager DELETE:urlString parameters:para success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"responseObject:%@",responseObject);
        if (responseObject){
            HYBaseNetworkModel *baseModel = [HYBaseNetworkModel modelWithDictionary:responseObject];
            
            if ([baseModel.code isEqualToString:KSUCCESS]) {
                //成功
                successBlock(baseModel);
            }
            else{
                
                [JRToast showWithText:baseModel.msg bottomOffset:60 duration:2.0];
                successBlock(nil);
            }
        }
        else{
            [JRToast showWithText:NSLocalizedString(@"interfaceError", nil) bottomOffset:60 duration:2.0];
            successBlock(nil);
        }
        
        if (view) [MBProgressHUD hidePregressHUD:view];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Error:%@",error);
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [JRToast showWithText:NSLocalizedString(@"serverError", nil) bottomOffset:60 duration:2.0];
            if (view) [MBProgressHUD hidePregressHUD:view];
            
        });
        successBlock(nil);
    }];
}

#pragma mark -- PUT

-(void)putDataFromUrl:(NSString *)url withParameter:(NSDictionary *)para showHUDView:(UIView *)view success:(requestSuccess)successBlock{
    if (view) [MBProgressHUD showPregressHUD:view];
    
    NSString *urlString= [NSString stringWithFormat:@"%@/%@",API_DomainStr,url];
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/plain", nil];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    // 设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 10.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    NSString *token = @"";
    NSTimeInterval currentTimeStamp = [[NSDate date] timeIntervalSince1970] * 1000;
    NSString *timestamp = [NSString stringWithFormat:@"%.0f",currentTimeStamp];
    //    if ([HYUserModel sharedInstance].token) {
    //        token = [NSString stringWithFormat:@"token %@",[HYUserModel sharedInstance].token];
    //    }
    //    [manager.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:timestamp forHTTPHeaderField:@"Access-TimeSpan"];
    
    NSLog(@"URL:%@\nPara:%@ \n",urlString,para);
    [manager PUT:urlString parameters:para success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"responseObject:%@",responseObject);
        if (responseObject){
            HYBaseNetworkModel *baseModel = [HYBaseNetworkModel modelWithDictionary:responseObject];
            
            if ([baseModel.code isEqualToString:KSUCCESS]) {
                //成功
                successBlock(baseModel);
            }
            else{
                
                [JRToast showWithText:baseModel.msg bottomOffset:60 duration:2.0];
                successBlock(nil);
            }
        }
        else{
            [JRToast showWithText:NSLocalizedString(@"interfaceError", nil) bottomOffset:60 duration:2.0];
            successBlock(nil);
        }
        
        if (view) [MBProgressHUD hidePregressHUD:view];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Error:%@",error);
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [JRToast showWithText:NSLocalizedString(@"serverError", nil) bottomOffset:60 duration:2.0];
            if (view) [MBProgressHUD hidePregressHUD:view];
            
        });
        successBlock(nil);
    }];
}

@end
